当使用RestTemplateBuilder
构建RestTemplate
时,可以通过RestTemplateCustomizer
进行更高级的定制,所有RestTemplateCustomizer
beans将自动添加到自动配置的RestTemplateBuilder
。此外,调用additionalCustomizers(RestTemplateCustomizer…)
方法可以创建一个新的,具有其他customizers的RestTemplateBuilder
。
以下示例演示使用自定义器(customizer)配置所有hosts使用代理,除了192.168.0.5
:
static class ProxyCustomizer implements RestTemplateCustomizer {
@Override
public void customize(RestTemplate restTemplate) {
HttpHost proxy = new HttpHost("proxy.example.com");
HttpClient httpClient = HttpClientBuilder.create()
.setRoutePlanner(new DefaultProxyRoutePlanner(proxy) {
@Override
public HttpHost determineProxy(HttpHost target,
HttpRequest request, HttpContext context)
throws HttpException {
if (target.getHostName().equals("192.168.0.5")) {
return null;
}
return super.determineProxy(target, request, context);
}
}).build();
restTemplate.setRequestFactory(
new HttpComponentsClientHttpRequestFactory(httpClient));
}
}